﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hardanger.Model;
using System.IO;

namespace Hardanger.Utils
{
    public static class FiddlerSessionParser
    {
        /// <summary>
        /// Creates a new Hardanger session
        /// </summary>
        /// <param name="id"></param>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="ssl"></param>
        /// <param name="request"></param>
        /// <returns>HardangerSession</returns>
         public static HardangerSession ParseFiddlerSession(int id, string host, int port, bool ssl, string request)
        {
            HardangerSession hs = new HardangerSession();
            hs.FiddlerId = id;
            hs.Hostname = host;
            hs.Port = port;
            hs.SSL = ssl;

            using (StringReader sr = new StringReader(request))
            {
                //Extracts the Command from the request and assigns the Method, HttpVersion and Get Paramaters to the HardangerSession
                ParseHttpCommand(hs, sr); 

                //Extracts the Header and POST data from the request and assigns them to the HardangerSession
                ParseHeaderAndBody(hs, sr);
            }
            return hs;
        }

        private static void ParseHeaderAndBody(HardangerSession hs, StringReader sr)
        {
            while (sr.Peek() >= 0)
            {
                string line = sr.ReadLine();
                if (string.IsNullOrEmpty(line))
                {
                    //we are done reading headers
                    hs.Post.Raw = sr.ReadToEnd();
                    break;
                }
                string[] parts = line.Split(new char[] { ':' }, 2);
                hs.Headers.Add(parts[0], parts[1].TrimStart(new char [] {' '}));
            }
        }

        private static void ParseHttpCommand(HardangerSession hs, StringReader sr)
        {
            hs.HttpCommand = sr.ReadLine();
            List<String> cmdParts = hs.HttpCommand.Split(' ').ToList();
            hs.Method = cmdParts[0];
            hs.HttpVersion = cmdParts.Last();
            
            string PathAndGet = String.Join("", cmdParts.GetRange(1, cmdParts.Count - 2).ToArray());
            string[] parts = PathAndGet.Split(new char[] { '?' }, 2);
            hs.Path = parts[0];
            if (parts.Length > 1)
            {
                hs.Get.Raw = parts[1];
            }
        }
    }
}
